package com.lkj.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lkj.utils.Ftputil;

@RequestMapping("/SpringMVC006")
@Controller
public class UploadTest {

	/*
	 * 采用file.Transto 来保存上传的文件
	 */
	/*
	 * 采用spring提供的上传文件的方法
	 */
	@RequestMapping("/springUpload")
	public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				System.out.println(file.getName());
				if (file != null) {
					InputStream fileIn = file.getInputStream();
					boolean flag = Ftputil.uploadFile("192.168.0.101", 21, "hl", "123456", "/home/hl/Videos", "aa.mp4", fileIn);
				}

			}

		}
		return "/success";
	}
}
